/*
动态水面系统
支持波纹、反射和钓鱼交互
为VR钓鱼游戏优化
*/

import * as THREE from 'three';

class WaterSurface {
  constructor(scene, options = {}) {
    this.scene = scene;
    
    // 默认配置
    this.config = {
      size: 100,
      segments: 200,
      color: 0x006994,
      transparency: 0.7,
      waveSpeed: 0.5,
      waveHeight: 0.3,
      rippleIntensity: 0.8,
      ...options
    };
    
    this.water = null;
    this.ripples = [];
    this.time = 0;
    
    this.init();
  }
  
  init() {
    this.createWaterSurface();
    this.createWaterMaterial();
    this.setupRippleSystem();
  }
  
  createWaterSurface() {
    // 创建水面几何体
    const geometry = new THREE.PlaneGeometry(
      this.config.size, 
      this.config.size, 
      this.config.segments, 
      this.config.segments
    );
    
    geometry.rotateX(-Math.PI / 2); // 水平放置
    
    // 存储原始顶点位置用于波浪动画
    this.originalPositions = geometry.attributes.position.array.slice();
    
    this.waterGeometry = geometry;
  }
  
  createWaterMaterial() {
    // 创建水面材质
    const waterMaterial = new THREE.MeshPhongMaterial({
      color: this.config.color,
      transparent: true,
      opacity: this.config.transparency,
      side: THREE.DoubleSide,
      shininess: 100,
      specular: 0x222222
    });
    
    // 创建水面网格
    this.water = new THREE.Mesh(this.waterGeometry, waterMaterial);
    this.water.receiveShadow = true;
    this.water.position.y = 0;
    
    this.scene.add(this.water);
  }
  
  setupRippleSystem() {
    // 涟漪系统初始化
    this.ripples = [];
    this.maxRipples = 10;
  }
  
  // 创建涟漪效果
  createRipple(x, z, intensity = 1) {
    const ripple = {
      x: x,
      z: z,
      radius: 0,
      maxRadius: 5 * intensity,
      intensity: intensity,
      speed: 2,
      life: 1.0,
      decay: 0.015
    };
    
    this.ripples.push(ripple);
    
    // 限制涟漪数量
    if (this.ripples.length > this.maxRipples) {
      this.ripples.shift();
    }
    
    console.log(`🌊 创建涟漪: (${x.toFixed(1)}, ${z.toFixed(1)}) 强度: ${intensity}`);
  }
  
  // 更新波浪动画
  updateWaves(deltaTime, waterTime) {
    this.time += deltaTime;
    
    const positions = this.waterGeometry.attributes.position.array;
    const originalPositions = this.originalPositions;
    
    // 基础波浪动画
    for (let i = 0; i < positions.length; i += 3) {
      const x = originalPositions[i];
      const z = originalPositions[i + 2];
      
      // 多层波浪效果
      let waveHeight = 0;
      waveHeight += Math.sin(x * 0.1 + waterTime * this.config.waveSpeed) * this.config.waveHeight;
      waveHeight += Math.cos(z * 0.15 + waterTime * this.config.waveSpeed * 0.8) * this.config.waveHeight * 0.5;
      waveHeight += Math.sin((x + z) * 0.08 + waterTime * this.config.waveSpeed * 1.2) * this.config.waveHeight * 0.3;
      
      // 添加涟漪效果
      this.ripples.forEach(ripple => {
        const distance = Math.sqrt((x - ripple.x) ** 2 + (z - ripple.z) ** 2);
        
        if (distance <= ripple.radius && distance >= ripple.radius - 1) {
          const rippleEffect = Math.sin((distance - ripple.radius) * Math.PI) * 
                              ripple.intensity * 
                              ripple.life * 
                              this.config.rippleIntensity;
          waveHeight += rippleEffect;
        }
      });
      
      positions[i + 1] = waveHeight;
    }
    
    // 更新涟漪
    this.ripples = this.ripples.filter(ripple => {
      ripple.radius += ripple.speed * deltaTime;
      ripple.life -= ripple.decay;
      return ripple.life > 0 && ripple.radius < ripple.maxRadius;
    });
    
    // 更新几何体
    this.waterGeometry.attributes.position.needsUpdate = true;
    this.waterGeometry.computeVertexNormals();
  }
  
  // 检测钓鱼点击
  detectFishingClick(raycaster) {
    const intersects = raycaster.intersectObject(this.water);
    
    if (intersects.length > 0) {
      const point = intersects[0].point;
      this.createRipple(point.x, point.z, 1.5);
      
      return {
        hit: true,
        position: point,
        distance: intersects[0].distance
      };
    }
    
    return { hit: false };
  }
  
  // 模拟鱼咬钩的水面扰动
  createFishBite(x, z, intensity = 2) {
    // 连续创建多个涟漪模拟鱼的活动
    this.createRipple(x, z, intensity);
    
    setTimeout(() => {
      this.createRipple(x + Math.random() - 0.5, z + Math.random() - 0.5, intensity * 0.7);
    }, 200);
    
    setTimeout(() => {
      this.createRipple(x + Math.random() - 0.5, z + Math.random() - 0.5, intensity * 0.5);
    }, 400);
  }
  
  // 获取指定位置的水面高度
  getWaterHeight(x, z) {
    // 计算水面在指定位置的高度（包括波浪）
    let height = 0;
    height += Math.sin(x * 0.1 + this.time * this.config.waveSpeed) * this.config.waveHeight;
    height += Math.cos(z * 0.15 + this.time * this.config.waveSpeed * 0.8) * this.config.waveHeight * 0.5;
    height += Math.sin((x + z) * 0.08 + this.time * this.config.waveSpeed * 1.2) * this.config.waveHeight * 0.3;
    
    return height;
  }
  
  // 设置水面颜色（根据天气、时间等）
  setWaterColor(color) {
    if (this.water && this.water.material) {
      this.water.material.color.setHex(color);
    }
  }
  
  // 设置水面透明度
  setWaterOpacity(opacity) {
    if (this.water && this.water.material) {
      this.water.material.opacity = opacity;
    }
  }
  
  // 销毁水面
  destroy() {
    if (this.water) {
      this.scene.remove(this.water);
      this.waterGeometry.dispose();
      this.water.material.dispose();
    }
    
    this.ripples = [];
  }
  
  // 更新方法（在游戏循环中调用）
  update(deltaTime, waterTime) {
    this.updateWaves(deltaTime, waterTime);
  }
}

export { WaterSurface }; 